package org.dreamwork.android.concurrent;

import android.os.Handler;
import android.os.Message;

/**
 * android.os.Handler 的代理类，主要是方便在 Activity/Fragment/Service 中使用.
 *
 * <p>使用方式：
 * Activity/Fragment/Service 实现 {@link IMessageHandler} 接口，并代理给该类
 * <pre>
 *     public MyActivity extends Activity implements IMessageHandler {
 *         private Handler handler;
 *
 *         public MyActivity () {
 *             handler = new MessageHandlerDelegate (this);
 *         }
 *
 *         &#64;Override
 *         public void handleUIMessage (Message message) {}
 *
 *         &#64;Override
 *         public handleNonUIMessage (Message message) {}
 *
 *         ...
 *     }
 * </pre>
 * </p>
 *
 * Created by game on 2016/9/7
 */
public class MessageHandlerDelegate extends Handler {
    private IMessageHandler handler;

    public MessageHandlerDelegate (IMessageHandler handler) {
        this.handler = handler;
    }

    public Message obtain () {
        return obtainMessage ();
    }

    public Message obtain (int what) {
        return obtainMessage (what);
    }

    public Message obtain (int what, Object obj) {
        return obtainMessage (what, obj);
    }

    public Message obtain (int what, int arg1, int arg2) {
        return obtainMessage (what, arg1, arg2);
    }

    public Message obtain (int what, int arg1, int arg2, Object obj) {
        return obtainMessage (what, arg1, arg2, obj);
    }

    public void sendUIMessage (int what) {
        sendEmptyMessage (what);
    }

    public void sendUIMessage (Message message) {
        sendMessage (message);
    }

    @Override
    public void handleMessage (Message msg) {
        handler.handleUIMessage (msg);
    }

    public void sendNonUIMessage (int what) {
        sendNonUIMessage (obtain (what));
    }

    public void sendNonUIMessage (int what, Object obj) {
        sendNonUIMessage (obtain (what, obj));
    }

    public void sendNonUIMessage (final Message message) {
        InternalRunner runner = new InternalRunner (handler, message);
        NonUILooper.runInNonUIThread (runner);
    }

    private static final class InternalRunner implements Runnable {
        private IMessageHandler handler;
        private Message message;

        InternalRunner (IMessageHandler handler, Message message) {
            this.handler = handler;
            this.message = message;
        }

        @Override
        public void run () {
            handler.handleNonUIMessage (message);
        }
    }
}